import React, { useRef } from 'react';
import { useDebounceEffect } from 'ahooks';
import { Addon, Node } from '@antv/x6';
import { ModuleConfig } from '../../types';
import { getConfig, appendOptions } from './tools';

interface ListProps {
  assets: { [key: string]: string };
  configs: ModuleConfig;
  onNodeCreate: (node: Node) => void;
  graph: any;
  defaultNodeShape: string;
  moduleNodeShape: string;
}

const List: React.FC<ListProps> = function ({
  onNodeCreate,
  configs,
  graph,
  assets,
  defaultNodeShape,
  moduleNodeShape,
}) {
  const listRef = useRef<HTMLDivElement>(null);

  const initPage = (graph, configs) => {
    if (!graph || !configs || !listRef.current) return;
    const stencilConfig = getConfig(
      graph,
      configs,
      assets,
      onNodeCreate,
      defaultNodeShape,
    );
    // #region 初始化 stencil
    const stencil = new Addon.Stencil(stencilConfig);
    appendOptions(graph, stencil, configs.options, assets, moduleNodeShape);
    listRef.current!.appendChild(stencil.container);
  };

  useDebounceEffect(
    () => {
      initPage(graph, configs);
    },
    [graph, configs],
    { wait: 100 },
  );

  return (
    <div
      className={`ra-arch-list ${configs.title ? '' : 'without-title'}`}
      ref={listRef}
    ></div>
  );
};

export default React.memo(List);
